import { Button, Form, message } from 'antd';
import ProForm, { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import type { CurrentUser } from '@/pages/admin/UserManager/components/data';
import UploadAvatar from '@/components/UploadAvatar';
import { updateUser } from '@/services/user';
const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
interface UpdateFormProps {
  setRefreshCount: any;
  formVals: CurrentUser;
}
const UpdateModalForm = (props: UpdateFormProps) => {
  const { formVals, setRefreshCount } = props;
  const [form] = Form.useForm();

  /**
   * 更新节点
   * @param fields
   */
  const handleUpdate = async (fields: CurrentUser) => {
    const hide = message.loading('正在更新');
    try {
      const res = await updateUser({
        ...fields,
      });
      hide();
      if (res.success) {
        setRefreshCount((count: any) => count + 1);
        message.success('更新成功');
      } else {
        message.error('更新失败,请重试');
      }
      return true;
    } catch (error) {
      hide();
      message.error('更新失败,请重试');
      return false;
    }
  };
  return (
    <ModalForm
      form={form}
      layout="horizontal"
      {...formLayout}
      title="编辑用户信息"
      modalProps={{
        onCancel: () => form.resetFields(),
      }}
      initialValues={{
        avatar: formVals.avatar,
        username: formVals.username,
        phone_number: formVals.phone_number,
        role: formVals.role,
      }}
      trigger={<Button type="primary">编辑</Button>}
      onFinish={async () => {
        form
          .validateFields()
          .then((fieldsValue) => {
            handleUpdate({
              ...fieldsValue,
              ID: formVals.ID,
            });
          })
          .catch(() => {});
        return true;
      }}
    >
      <ProForm.Item
        key="avatar"
        name="avatar"
        label="图片"
        getValueFromEvent={(e) => {
          return e.response.url;
        }}
        rules={[{ required: true, message: '请上传图片' }]}
      >
        <UploadAvatar forValue="avatar" />
      </ProForm.Item>
      <ProFormText
        key="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        rules={[{ required: true, message: '请输入用户名', min: 1, max: 20 }]}
        width={256}
      />
      <ProFormText
        key="phone_number"
        name="phone_number"
        label="电话号码"
        placeholder="请输入电话号码"
        width={256}
      />
      <ProFormSelect
        key="role"
        name="role"
        label="角色类型"
        placeholder="请选择角色类型"
        width={256}
        options={[
          { label: '顾客', value: 'customer' },
          { label: '员工', value: 'staff' },
          { label: '管理员', value: 'admin' },
        ]}
      />
    </ModalForm>
  );
};
export default UpdateModalForm;
